import React, {
  Component,
} from 'react';
import {
  observable,
  action,
  computed,
  toJS,
} from 'mobx';
import { Button } from 'antd';
import TimeView from '../components/newOutside/TimeView';
import MapView from '../components/newOutside/MapView';
import Detailed from '../components/newOutside/Detailed';
import Table from '../components/newOutside/Table';

import * as API from '../apis/outside';
import moment from 'moment';
import {
  fetch,
  getTopButtons,
  getDropMenuDatas,
  getMenusCreationConfig,
  componentReset,
  exportExcel,
} from '../../hrmAttendance/util/save-time-util.js';
import {
  WeaTools,
  WeaLocaleProvider,
} from 'ecCom';
import {
  WeaTableNew,
} from 'comsMobx';
import {
  i18n,
} from '../public/i18n';

const {
  TableStore,
} = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;

export class newHrmOutSide {
  signTitle = () => getLabel('516948', '显示移动端考勤记录');
  @observable _selectedTabIndex = '0';
  @observable temp = true;
  @observable userRoot = undefined;
  @observable orgTreeIsMult = '0';
  @observable orgTreeCheckedDatas = [];
  @observable loading = false;
  @observable radioGroupParams = {};
  @observable showSignInfo = '0';
  @observable hrmId = '';
  @observable hasRight = true;
  @observable mapData = [];
  @observable timeData = [];
  @observable visible = false;
  @observable positionObj = {};
  @observable dateTabkey = '1';
  @observable pDate = new moment().format('YYYY-MM-DD');
  @observable table = new TableStore();
  @observable config = [];
  @observable dataKey = '';
  @observable hrmName = WeaTools.ls.getJSONObj('theme-account') && WeaTools.ls.getJSONObj('theme-account').username || undefined;


  // tab标签
  @computed get selectedTabIndex() {
    return this._selectedTabIndex;
  }
  // 顶部按钮
  @computed get topButton() {
    return this.selectedTabIndex == '2' ? [
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@p7rja4@1`} type="primary" onClick={() => { this.exportexcel(this.dataKey); }}>{i18n.button.export()}</Button>),
    ]
    :
    [];
  }
  // 顶部菜单下拉按钮显示导出功能
  @computed get dropMenuDatas() {
    return this.selectedTabIndex == '2' ? [
      {
        key: '1',
        icon: <i className="icon-coms-export" />,
        content: i18n.button.export(),
        onClick: () => {
          this.exportexcel(this.dataKey);
        },
      },
    ]
    :
    [];
  }
  // 右键菜单显示导出功能
  @computed get rightMenu() {
    return this.selectedTabIndex == '2' ? [
      {
        key: '1',
        icon: <i className="icon-coms-export" />,
        content: i18n.button.export(),
        onClick: () => {
          this.exportexcel(this.dataKey);
        },
      },
    ]
    :
    [];
  }
  // 初始化数据
  @action
  init = () => {
    this.hrmId = undefined;
    this.showSignInfo = '0';
    this.tabkey = '1';
    this.dateTabkey = '1';
    this.visible = false;
    this.pDate = new moment().format('YYYY-MM-DD');
    this.hrmName = WeaTools.ls.getJSONObj('theme-account') && WeaTools.ls.getJSONObj('theme-account').username || undefined;
    this.userRoot = [];
    this.orgTreeIsMult = '0';
    this.orgTreeCheckedDatas = [];
    this._selectedTabIndex = '0';
    // this.getOsInfo();
  }

  redraw = () => {}

  getOsInfo = async () => {
    let data = await WeaTools.callApi('/api/system/info/getOSinfo', 'GET', {});
    if(data.status){
        data.mapParams.ableToSwitchMap = "true";
        localStorage.setItem('getOsInfo', JSON.stringify(data));
    }
  }

  @action tabName = (newOutSide) => {
    if (this.selectedTabIndex == '0') {
      return (<TimeView ecId={`${this && this.props && this.props.ecId || ''}_TimeView@1vn7g7`} newOutSide={newOutSide} />);
      }
      if (this.selectedTabIndex == '1') {
        return (<MapView ecId={`${this && this.props && this.props.ecId || ''}_MapView@p5ghjk`} newOutSide={newOutSide} />);
      }
      if (this.selectedTabIndex == '2') {
        return (<Detailed ecId={`${this && this.props && this.props.ecId || ''}_Detailed@9vnro9`} newOutSide={newOutSide} />);
      }
    }

    // --------------------------左侧树-----------------------
    @action
    updateOrgTreeIsMult = (v) => {
      this.orgTreeIsMult = v;
    }
    @action
    updateOrgTreeCheckedDatas = (v = []) => {
      this.orgTreeCheckedDatas = v;
    }
    @action
    updateUserRoot = (data) => {
      this.userRoot = data;
      if (data.length > 0) {
        this.hrmId = data[0].id;
      }
      if (this.hrmId) {
        this.getData();
      }
    }
    @action
    updateHrmId = (v) => {
      this.hrmId = v;
    }
    @action
    updateHrmName = (v) => {
      this.hrmName = v || WeaTools.ls.getJSONObj('theme-account') && WeaTools.ls.getJSONObj('theme-account').username || undefined;
    }

    // 请求数据
    @observable lastParams = {};

    @action refreshData = async () => {
      const datas = await this.getData();
      this.selectedTabIndex == '1' && this.redraw();
    }

    @action
    getData = async (param) => {
      let params = param || {};
      if (this.loading) { return; }
      this.loading = true;
      if (params == null) {
        params = toJS(this.lastParams);
      } else {
        this.lastParams = params;
      }

      if (this.hrmId) {
        params.resourceId = this.hrmId;
      }
      params.loaddata = '1';
      if (this.selectedTabIndex == '2') {
        if (!params.typeselect || params.typeselect == '') params.typeselect = 1;
        if (!params.signtype || params.signtype == '') params.signtype = 2;
        params.cmd = 'detialData';
      } else {
        params.fromDate = this.pDate;
        params.toDate = this.pDate;
        params.signtype = this.showSignInfo;
        if (this.selectedTabIndex == '0') {
          params.cmd = 'timeData';
        } else if (this.selectedTabIndex == '1') {
          params.cmd = 'mapData';
        }
      }


      const datas = await API.getHrmMobileSignInInfo(params);
        // 测试要求明细页面权限放开
      if (this.selectedTabIndex == '0') {
        if (datas.status == '1') {
          this.hasRight = true;
          this.timeData = datas.result || [];
        } else {
          this.hasRight = false;
        }
      } else if (this.selectedTabIndex == '1') {
        if (datas.status == '1') {
          this.hasRight = true;
          this.mapData = datas.result || [];
          // this.redraw();
        } else {
          this.hasRight = false;
        }
      } else if (this.selectedTabIndex == '2') {
          this.hasRight = true;
          this.table = new TableStore();
          this.table.getDatas(datas.sessionkey, 1);
          this.dataKey = datas.sessionkey;
      }

      this.loading = false;
      return datas;
    }

    // -------------------------------------------------------地图-------------------------------------
    @action
    updatePosition = (obj) => {
      this.positionObj = obj;
    }
    @action
    updateVisible = (v) => {
      this.visible = v;
    }
    // ---------------------------------------日期------------------------------------------

    @action
    changeDateTab = (key) => {
      this.dateTabkey = key;
      const current = new moment();
      if (key == 1) {
        this.pDate = current.format('YYYY-MM-DD');
      } else if (key == 2) {
        this.pDate = current.subtract(1, 'days').format('YYYY-MM-DD');
      } else {
        this.pDate = current.format('YYYY-MM');
      }
    }

    @action
    changeDate = (value) => {
      this.pDate = value;
    }


    @action getRadioGroupConfig = () => {
      API.getSearchCondition().then((resp) => {
        const {
          condition,
        } = resp;
        const configfirstrow = {
          label: i18n.label.date(),
          options: [{
            key: '0',
            showname: i18n.label.all(),
          }, {
            key: '1',
            showname: i18n.label.today(),
            selected: true,
          }, {
            key: '2',
            showname: i18n.label.tswk(),
          }, {
            key: '3',
            showname: i18n.label.tsmth(),
          }, {
            key: '4',
            showname: i18n.label.tssn(),
          }, {
            key: '5',
            showname: i18n.label.tsyr(),
          }, {
            key: '7',
            showname: i18n.label.preMonth(),
          }, {
            key: '8',
            showname: i18n.label.preYear(),
          }, {
            key: '6',
            showname: i18n.label.dateRange(),
          }],
          domkey: ['typeselect'],
          selectLinkageDatas: {
            6: {
              conditionType: 'RANGEPICKER',
              domkey: ['fromDate', 'toDate'],
            },
          },
          labelcol: 4,
          fieldcol: 20,
        };

        condition[0].items.unshift(configfirstrow);

        this.config = condition[0].items;
      });
      this.temp = false;

      // 清空左侧树选择的人员id，明细页只能看到当前账户人员
      this.hrmId = undefined;

      // this.getData()
    }

    @action
    handleCheckbox = (v) => {
      this.showSignInfo = v;
      this.refreshData();
    }

    // Table的查看
    handleViewClick = (id) => {
      API.getShowSignImg({
        id,
      }).then((datas) => {
        const {
          signImgIds,
        } = datas;

        if (signImgIds) {
          const imgPool = signImgIds.split(',').map(id => `/weaver/weaver.file.FileDownload?fileid=${id}`);
          const indexNum = 0;

          if (window.IMCarousel) {
            window.IMCarousel.showImgScanner4Pool(true, imgPool, indexNum, null, window.top);
          } else {
            loadjs(['/social/js/drageasy/drageasy.js', '/social/js/bootstrap/js/bootstrap.js?v=20171218', '/social/im/js/IMUtil_wev8.js', '/social/js/imcarousel/imcarousel.js'], () => {
              window.IMCarousel.showImgScanner4Pool(true, imgPool, indexNum, null, window.top);
            });
          }
        }
      });
    }

    // 导出
    @action
  exportexcel(dataKey) {
    // this.table.exportAll('',this.title);
    this.table.exportAll();
  }
  }
